package fi.internetix.edelphi.liveillustrator;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletContextEvent;

import org.hsqldb.persist.HsqlProperties;
import org.hsqldb.server.Server;
import org.hsqldb.server.ServerAcl.AclFormatException;
import org.hsqldb.server.ServerConfiguration;

public class ServletContextListener implements javax.servlet.ServletContextListener {

  public void contextDestroyed(ServletContextEvent ctx) {
    server.stop();
  }

  public void contextInitialized(ServletContextEvent servletContextEvent) {
    try {
      Class.forName("org.hsqldb.jdbcDriver");  
      
      HsqlProperties props = new HsqlProperties();
      ServerConfiguration.translateDefaultDatabaseProperty(props);
      props.setProperty("server.database.0", "mem:ldi");
      server.setProperties(props);
      server.start();
      createTables();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (AclFormatException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  
  private void createTables() throws SQLException {
    Connection c = Utils.getConnection();
    Statement statement = c.createStatement();
    statement.execute("CREATE MEMORY TABLE PUBLIC.CONTROL (id BIGINT, ACTION VARCHAR(255), ARGS VARCHAR(255))");
    c.close();
  }

  private Server server = new Server();
}
